/* eslint-disable node/prefer-global/process */
/* eslint-disable no-console */
/* eslint-disable perfectionist/sort-imports */
import cors from 'cors'
import dotenv from 'dotenv'
import express from 'express'
import helmet from 'helmet'
import morgan from 'morgan'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

import { connectDB } from './config/database.js'
// 导入配置
import config from './config/index.js'
// 导入中间件
import { errorHandler } from './middleware/errorHandler.js'
import { rateLimiter } from './middleware/rateLimiter.js'

import { setContentType, staticAssetsCors } from './middleware/staticAssets.js'
// 导入路由
import adminRoutes from './routes/admin.js'
import domainRoutes from './routes/domain.js'

import expertRoutes from './routes/expert.js'
import mobileRoutes from './routes/mobile.js'
import openGatewayRoutes from './routes/open-gateway.js'
import orderRoutes from './routes/order.js'
import previewRoutes from './routes/preview.js'
import questionRoutes from './routes/question.js'
import redeemCodeRoutes from './routes/redeemCode.js'
import serviceIntegrationRoutes from './routes/service-integration.js'
import taskRoutes from './routes/task.js'
import userRoutes from './routes/user.js'
import { createDefaultAdmin } from './scripts/init-admin.js'
import { preloadImageUrlTemplate } from './utils/imageUrl.js'

// 获取当前文件目录
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// 加载环境变量
dotenv.config()

const app = express()
const PORT = process.env.PORT || 3000

// 基础中间件
app.use(helmet({
  upgradeInsecureRequests: false,
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ['\'self\''],
      scriptSrc: ['\'self\'', '\'unsafe-inline\'', 'https:'],
      styleSrc: ['\'self\'', '\'unsafe-inline\'', 'https:'],
      imgSrc: ['\'self\'', 'data:', 'https:'],
      connectSrc: ['\'self\'', 'https:', 'http:'],
      fontSrc: ['\'self\'', 'https:'],
      objectSrc: ['\'none\''],
      mediaSrc: ['\'self\''],
      frameSrc: ['\'none\''],
    },
  },
  crossOriginOpenerPolicy: false,
  crossOriginResourcePolicy: false,

}))
// 配置CORS - 为upload路径提供更宽松的跨域策略
app.use('/uploads', cors({
  origin: '*', // 允许所有域名访问upload资源
  methods: ['GET', 'HEAD', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'Range'],
  exposedHeaders: ['Content-Length', 'Content-Range', 'Accept-Ranges'],
  credentials: false, // upload资源不需要凭证
}))

// 其他路径使用严格的CORS策略
app.use(cors({
  origin: config.cors.origin,
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
  exposedHeaders: ['X-Total-Count'],
}))
app.use(morgan('combined'))
app.use(express.json({ limit: '10mb' }))
app.use(express.urlencoded({ extended: true, limit: '10mb' }))

// 配置EJS模板引擎
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views'))

// 静态文件服务 - 优化的upload资源服务
app.use('/uploads', staticAssetsCors, setContentType, express.static(path.join(__dirname, 'uploads'), {
  maxAge: '1y', // 1年缓存
  etag: true, // 启用ETag
  lastModified: true, // 启用Last-Modified
  index: false, // 禁用目录索引
  dotfiles: 'deny', // 拒绝访问隐藏文件
}))

// 速率限制
app.use(rateLimiter)

// 手机端API路由（小程序专用）
app.use('/api/mobile', mobileRoutes)

// 管理后台API路由
app.use('/api/admin', adminRoutes)
app.use('/api/user', userRoutes)
app.use('/api/domains', domainRoutes)
app.use('/api/experts', expertRoutes)
app.use('/api/questions', questionRoutes)
app.use('/api/orders', orderRoutes)
app.use('/api/redeem-codes', redeemCodeRoutes)
app.use('/api/service-integrations', serviceIntegrationRoutes)
app.use('/api/tasks', taskRoutes)

// 预览页面路由（后端渲染）
app.use('/preview', previewRoutes)

// 开放网关路由（支付回调等）
app.use('/open-gateway', openGatewayRoutes)

// 健康检查
app.get('/health', (_req, res) => {
  res.json({
    code: 200,
    message: 'Service is healthy',
    data: {
      status: 'OK',
      timestamp: new Date().toISOString(),
      environment: process.env.NODE_ENV || 'development',
    },
  })
})

// 404处理 - 只处理API路由
app.use('/api/*', (_req, res) => {
  res.status(404).json({
    code: 404,
    message: 'API endpoint not found',
    data: null,
  })
})

// 其他路由的404处理
app.use('*', (_req, res) => {
  res.status(404).send(`
    <!DOCTYPE html>
    <html>
    <head>
      <title>页面不存在 - 彼知AI</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <style>
        body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
        h1 { color: #dc3545; }
        a { color: #667eea; text-decoration: none; }
        a:hover { text-decoration: underline; }
      </style>
    </head>
    <body>
      <h1>404 - 页面不存在</h1>
      <p>您访问的页面不存在</p>
      <a href="/preview">返回预览首页</a>
    </body>
    </html>
  `)
})

// 错误处理中间件
app.use(errorHandler)

// 启动服务器
async function startServer() {
  try {
    // 连接数据库
    await connectDB()

    // 创建默认管理员
    await createDefaultAdmin()

    // 预加载图片URL模板
    await preloadImageUrlTemplate()

    app.listen(PORT, () => {
      console.log(`🚀 Server is running on port ${PORT}`)
      console.log(`📊 Environment: ${process.env.NODE_ENV || 'development'}`)
      console.log(`🔗 Health check: http://localhost:${PORT}/health`)
    })
  }
  catch (error) {
    console.error('❌ Failed to start server:', error)
    process.exit(1)
  }
}

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('SIGTERM received, shutting down gracefully')
  process.exit(0)
})

process.on('SIGINT', () => {
  console.log('SIGINT received, shutting down gracefully')
  process.exit(0)
})

startServer()

export default app
